using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


namespace ODM2KMZ
{
    public partial class MetadataDataset : System.Web.UI.Page
    {
        public string strPath
        {
            get
            {
                string str;

                str = !base.Request.Url.AbsoluteUri.Contains("?") ? base.Request.Url.AbsoluteUri : base.Request.Url.AbsoluteUri.Remove(base.Request.Url.AbsoluteUri.IndexOf("?"));
                return string.Concat(str.Replace(base.Request.Url.AbsolutePath, ""), base.Request.ApplicationPath);
            }
        }

        public string CurrentURL
        {
            get
            {
                if (base.Request.QueryString["URL"] != null)
                {
                    return base.Request.QueryString["URL"];
                }
                return ConfigurationManager.AppSettings["defaultWofService"];
            }
        }

        public string SiteCode
        {
            get
            {
                if (base.Request.QueryString["SiteCode"] != null)
                {
                    return base.Request.QueryString["SiteCode"];
                }
                return "CSIRO:6001";
                //return string.Empty;
            }
        }

        public string VariableCode
        {
            get
            {
                if (base.Request.QueryString["VariableCode"] != null)
                {
                    return base.Request.QueryString["VariableCode"];
                }
                return "100007-Cont";
                //return string.Empty;
            }
        }

        public string MethodID
        {
            get
            {
                if (base.Request.QueryString["MethodID"] != null)
                {
                    return base.Request.QueryString["MethodID"];
                }
                return "1";
                //return string.Empty;
            }
        }

        public string QualityControlLevelID
        {
            get
            {
                if (base.Request.QueryString["QualityControlLevelID"] != null)
                {
                    return base.Request.QueryString["QualityControlLevelID"];
                }
                return "0";
                //return string.Empty;
            }
        }

        public string SourceID
        {
            get
            {
                if (base.Request.QueryString["SourceID"] != null)
                {
                    return base.Request.QueryString["SourceID"];
                }
                return "1";
//                return string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = "Dataset Metadata";

        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            HtmlGenericControl MasterPageBodyTag;
            MasterPageBodyTag = (HtmlGenericControl)Master.FindControl("BodyID");
            MasterPageBodyTag.Attributes.Add("OnUnload", "GUnload()");
            MasterPageBodyTag.Attributes.Add("OnLoad", "Load();");
            GetMetadata();
        }
        private void GetMetadata()
        {

            WaterOneFlow waterOneFlow = initWaterOneFlow();

            SiteInfoResponseTypeSite siteInfoResponseTypeSite;
            // try
            //  {
            siteInfoResponseTypeSite = waterOneFlow.GetSiteInfoObject(SiteCode, String.Empty).site[0];
            
            loadSite(siteInfoResponseTypeSite.siteInfo);


            seriesCatalogTypeSeries[] SeriesCatalogTypeSeriess = siteInfoResponseTypeSite.seriesCatalog[0].series;
            for (int i = 0; i < (int)SeriesCatalogTypeSeriess.Length; i++)
            {
                seriesCatalogTypeSeries SeriesCatalogTypeSeries = SeriesCatalogTypeSeriess[i];
                if (checkSeries(SeriesCatalogTypeSeries).Equals(true))
                {
                    lObservationsCount.Text= SeriesCatalogTypeSeries.valueCount.Value.ToString();
                    lObservationsStartDate.Text = ((TimeIntervalType)SeriesCatalogTypeSeries.variableTimeInterval).beginDateTime.ToString("yyyy-MM-ddTHH:mm:ss");
                    lObservationsEndDate.Text = ((TimeIntervalType)SeriesCatalogTypeSeries.variableTimeInterval).endDateTime.ToString("yyyy-MM-ddTHH:mm:ss");
                    loadVariable(SeriesCatalogTypeSeries.variable);
                    loadMethod(SeriesCatalogTypeSeries.Method);
                    loadQualityControlLevel(SeriesCatalogTypeSeries.QualityControlLevel);
                    loadSource(SeriesCatalogTypeSeries.Source);

                    break;
                }
            }


        }

        private bool checkSeries(seriesCatalogTypeSeries SeriesCatalogTypeSeries)
        {
            bool ret = false;
            if (SeriesCatalogTypeSeries.variable.variableCode[0].Value.Equals(VariableCode) && SeriesCatalogTypeSeries.Method.methodID.ToString().Equals(MethodID) && SeriesCatalogTypeSeries.QualityControlLevel.QualityControlLevelID.ToString().Equals(QualityControlLevelID) && SeriesCatalogTypeSeries.Source.sourceID.ToString().Equals(SourceID) )
                ret = true;

            return ret;
                    
        }

        private DataTable initDataTable()
        {
            DataTable datatable = new DataTable();
            datatable.Columns.Add("Key");
            datatable.Columns.Add("Value");
            return datatable;
        }

        private WaterOneFlow initWaterOneFlow()
        {
            WaterOneFlow waterOneFlow = new WaterOneFlow();
            waterOneFlow.Url = CurrentURL;
            return waterOneFlow;
        }

        private void loadSite(SiteInfoType siteInfoType)
        {

            LatLonPointType latLongPointType = (LatLonPointType)siteInfoType.geoLocation.geogLocation;

            lSiteName.Text = siteInfoType.siteName;
            lSiteCode.Text = siteInfoType.siteCode[0].Value;
            lSiteCounty.Text = getNote(siteInfoType, "County");
            lSiteState.Text = getNote(siteInfoType, "State");
            lSiteComments.Text = getNote(siteInfoType, "Comments");

            lSiteLatitude.Text = latLongPointType.latitude.ToString();
            lSiteLongitude.Text = latLongPointType.longitude.ToString();
            lSiteSpatialReference.Text = latLongPointType.srs;

            try
            {
                lSiteElevation.Text = siteInfoType.elevation_m.ToString();
                lSiteVerticalDatum.Text = siteInfoType.verticalDatum;
            }
            catch { }


            if (siteInfoType.geoLocation.localSiteXY != null)
            {
                SiteInfoTypeGeoLocationLocalSiteXY siteInfoTypeGeoLocation = siteInfoType.geoLocation.localSiteXY[0];
                lSiteXLocalProjection.Text = siteInfoTypeGeoLocation.X.ToString();
                lSiteYLocalProjection.Text = siteInfoTypeGeoLocation.Y.ToString();
                lSiteProjection.Text = siteInfoTypeGeoLocation.projectionInformation;
            }

            SiteLatitude.Value = lSiteLatitude.Text;
            SiteLongitude.Value = lSiteLongitude.Text;
            SiteName.Value = lSiteName.Text;
            

        }

        private void loadVariable(VariableInfoType variableInfoType)
        {

            try
            {
                lVariableName.Text = variableInfoType.variableName;
            }
            catch { }
            try
            {
                lVariableCode.Text = variableInfoType.variableCode[0].Value;
            }
            catch { }
            try
            {
                lVariableUnits.Text = string.Format("{0} ({1})", variableInfoType.units.Value, variableInfoType.units.unitsAbbreviation);
            }
            catch { }
            try
            {
                lVariableSampleMedium.Text = variableInfoType.sampleMedium.ToString();
            }
            catch { }
            try
            {
                lVariableValueType.Text = variableInfoType.valueType.ToString();
            }
            catch { }
            try
            {
                lVariableIsRegular.Text = variableInfoType.timeSupport.isRegular.ToString();
            }
            catch { }
            try
            {
                lVariableTimeSupport.Text = variableInfoType.timeSupport.timeInterval.ToString();
            }
            catch { }
            try
            {
                lVariableTimeUnits.Text = string.Format("{0} ({1})", variableInfoType.timeSupport.unit.UnitDescription, variableInfoType.timeSupport.unit.UnitAbbreviation);
            }
            catch { }
            try
            {
                lVariableDataType.Text = variableInfoType.dataType.ToString();
            }
            catch { }
            try
            {
                lVariableGeneralCategory.Text = variableInfoType.generalCategory.ToString();
            }
            catch { }
            try
            {
                lVariableNoDataValue.Text = variableInfoType.NoDataValue.ToString();
            }
            catch { }

        }
        

        private void loadMethod(MethodType methodType)
        {
            lMethodDescription.Text = methodType.MethodDescription;
            lMethodLink.Text = methodType.MethodLink;
        }

        private void loadQualityControlLevel(QualityControlLevelType qualityControlLevelType)
        {
            lQualityControlLevel.Text = qualityControlLevelType.QualityControlLevelID.ToString();
            lQualityControlLevelDescription.Text = qualityControlLevelType.Value;
        }

        private void loadSource(SourceType sourceType)
        {

            ContactInformationType contactInformationType = sourceType.ContactInformation;
            MetaDataType metadataType = sourceType.Metadata;

            lSourceOrganisation.Text = sourceType.Organization;
            lSourceDescription.Text = sourceType.SourceDescription;
            lSourceLink.Text = sourceType.SourceLink;
            try
            {
                lSourceContactName.Text = contactInformationType.ContactName;
                lSourcePhone.Text = contactInformationType.Phone;
                lSourceEmail.Text = contactInformationType.Email;
                lSourceAddress.Text = contactInformationType.Address.ToString();
                //lSourceCity.Text =
                //lSourceState.Text =
                //lSourcePostCode.Text =
            }
            catch { }

            try
            {
                lSourceIsoMetadataTopicCategory.Text = metadataType.TopicCategory;
                lSourceIsoMetadataTitle.Text = metadataType.Title;
                lSourceIsoMetadataAbstract.Text = metadataType.Abstract;
                lSourceIsoMetadataProfileVersion.Text = metadataType.ProfileVersion;
                lSourceIsoMetadataMetadataLink.Text = metadataType.MetadataLink;
            }
            catch { }

        }

        private string getNote(SiteInfoType siteInfoType, string grouping)
        {
            int i;
            for (i = 0; i < siteInfoType.note.Length; i++)
            {
                if (siteInfoType.note[i].title == grouping)
                    return siteInfoType.note[i].Value;
            }
            return String.Empty;

        }
       


    }
}
